<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
      <el-form label-width="70px" size="small">
        <el-row :gutter="10">
          <el-col :lg="6" :md="8" :sm="12" :xl="6" :xs="24">
            <el-form-item label="关键字">
              <el-input
                  v-model="query.keyword"
                  class="filter-item"
                  clearable
                  placeholder="输入 客户编码/客户名称/助记符 搜索"
                  size="small"
                  style="width: 100%;"
                  @keyup.enter.native="crud.toQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xl="6" :xs="24">
            <el-form-item label="商品名称">
              <zSelect :value.sync="query.goodsId"  url="api/dropDown/basGoodsList" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xl="6" :xs="24">
            <el-form-item label="客户">
              <zSelect multiple :value.sync="query.customerIds" url="api/dropDown/basCustomerList" :params="{isContact:'0,2'}"
                       style="width:  100%;"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xl="6" :xs="24">
            <el-form-item label="二批">
              <table-select
                :tableColumns="
                  [
                  {prop:'code',label:'二批编码',width: '100'},
                  {prop:'name',label:'二批名称',width: '150'},
                  ]"
                labelKey="name"
                valueKey="id"
                width="400"
                :params="{type:3}"
                :value.sync="query.sCustomerIds"
                placeholder="请选择二批"
                url="api/dropDown/basCustomerList"
              ></table-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <rrOperation :crud="crud"/>
    </div>
    <crudOperation :permission="permission">
    </crudOperation>
    </div>
    <div class="body-container">
      <!--表单组件-->
      <el-dialog :append-to-body='true' :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="600px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
          <!--          <el-form-item label="编码" prop="code">-->
          <!--            <el-input v-model="form.code" style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="名称" prop="name">-->
          <!--            <el-input v-model="form.name" style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="客户合同价类型">-->
          <!--            <el-select v-model="form.type" class="edit-input" placeholder="请选择客户合同价类型" style="width: 370px;">-->
          <!--              <el-option-->
          <!--                  v-for="(item,index) in dict.t_bas_customer_contract_price_type"-->
          <!--                  :key="index"-->
          <!--                  v-if="item.seq>0"-->
          <!--                  :label="item.label"-->
          <!--                  :value="item.value"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item label="客户名称">
            <zSelect :value.sync="form.customerId" :showName="form.customerName" url="api/dropDown/basCustomerList" style="width:  370px;"
                     @change="changeCustomer"/>
          </el-form-item>
          <el-form-item label="客户编码">
            <el-input v-model="form.customerCode"  disabled style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="店内码">
            <el-input v-model="form.storeCode" style="width: 370px;"/>
          </el-form-item>

          <el-form-item label="商品名称" prop="goodsId">
            <zSelect :value.sync="form.goodsId" :showName="form.goodsName" valueKey="goodsId" labelKey="goodsName" url="/api/dropDown/basGoodsListForAdd" style="width:  370px;"
                     @change="changeGoods"/>
          </el-form-item>
          <el-form-item label="商品编码">
            <el-input v-model="form.goodsCode" disabled style="width: 370px;"/>
          </el-form-item>
          <!--          <el-form-item label="商品名称">-->
          <!--            <el-input v-model="form.goodsName" style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="条形码">-->
          <!--            <el-input v-model="form.barcode" style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="箱装条形码">-->
          <!--            <el-input v-model="form.boxBarcode" style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="助记符">-->
          <!--            <el-input v-model="form.helpSign" style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="规格型号">-->
          <!--            <el-input v-model="form.model" style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="商品品牌名称">-->
          <!--            &lt;!&ndash;            <zSelect :value.sync="form.goodsBrandId" url="api/dropDown/basGoodsBrandList" style="width:  370px;"/>&ndash;&gt;-->
          <!--            <el-input v-model="form.goodsBrandName" readonly disabled style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="商品分类名称">-->
          <!--            <el-input v-model="form.goodsTypeName" readonly disabled style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="商品类型名称">-->
          <!--            &lt;!&ndash;            <zSelect :value.sync="form.goodsTagId" url="api/dropDown/basGoodsTagList" style="width:  370px;"/>&ndash;&gt;-->
          <!--            <el-input v-model="form.goodsTagName" readonly disabled style="width: 370px;"/>-->
          <!--          </el-form-item>-->

          <el-form-item label="含税单价">
            <el-input v-model="form.taxPrice" style="width: 370px;" @input="changePrice(1)"/>
          </el-form-item>
          <el-form-item label="未税单价">
            <el-input v-model="form.noTaxPrice" readonly disabled style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="箱装量">
            <el-input v-model="form.boxUnitCount" readonly disabled style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="含税箱价">
            <el-input v-model="form.taxBoxPrice" style="width: 370px;" @input="changePrice(2)"/>
          </el-form-item>
          <el-form-item label="未税箱价">
            <el-input v-model="form.noTaxBoxPrice" readonly disabled style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="开单单价">
            <el-input v-model="form.billTaxPrice" style="width: 370px;" @input="billComputedPrice('billTaxPrice')"/>
          </el-form-item>
          <el-form-item label="开单箱价">
            <el-input v-model="form.billTaxBoxPrice" style="width: 370px;" @input="billComputedPrice('billTaxBoxPrice')"/>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="form.seq" :min="1" label="排序" style="width: 370px;"></el-input-number>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" class="edit-input" placeholder="请选择" style="width: 370px;">
              <el-option
                  v-for="(item,index) in dict.common_status"
                  :key="index"
                  v-if="item.seq>0"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
<!--          <el-form-item label="价格套价格">-->
<!--            <el-input v-model="form.noTaxBoxPrice" readonly disabled style="width: 370px;"/>-->
<!--          </el-form-item>-->
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" style="width: 370px;"/>
          </el-form-item>
        </el-form>
<!--        <el-table ref="priceTble"   :data="priceSuitList"  border style="width: 100%">-->
<!--          <el-table-column prop="priceSuitName"  align="center" width="180" label="价格套信息" />-->
<!--          <el-table-column prop="taxPrice" width="100" align="center" label="含税单价">-->
<!--            <template slot-scope="{ row }">{{ row.taxPrice.toFixed(2) }}</template>-->
<!--          </el-table-column>-->
<!--          <el-table-column width="100" align="center" prop="noTaxPrice" label="未税单价" >-->
<!--            <template slot-scope="{ row }">{{ row.noTaxPrice.toFixed(2) }}</template>-->
<!--          </el-table-column>-->
<!--          <el-table-column prop="taxBoxPrice" width="100" align="center" label="含税箱价" >-->
<!--            <template slot-scope="{ row }">{{ row.taxBoxPrice.toFixed(2) }}</template>-->
<!--          </el-table-column>-->
<!--          <el-table-column prop="noTaxBoxPrice" width="100" align="center" label="未税箱价" >-->
<!--            <template slot-scope="{ row }">{{ row.noTaxBoxPrice.toFixed(2) }}</template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>
      <!-- 表格配置 -->
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
      </el-dialog>

      <!--表格渲染-->

      <el-table ref="table"  border
                height="700"
                show-summary
                @cell-dblclick="row=>crud.toEdit(row)"
                v-loading="crud.loading"
                :data="crud.data"
                size="small"
                style="width: 100%;"
                v-if="isShowTable"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                :summary-method="crud.sumRow"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template v-if="item.prop =='sort'">
              <div class="handle_move">
                <i :class="scope.row['sort']" />
              </div>
            </template>
            <template v-else>
              <span v-if="item.type == 1" style="margin-left: 0px">{{scope.row[`${item.prop}`]}}</span>
              <span v-if="item.type == 2" style="margin-left: 0px">{{ parseTime(scope.row[`${item.prop}`])}}</span>
              <span v-if="item.type == 3" style="margin-left: 0px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
            </template>
          </template>
        </el-table-column>
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerCode')" prop="customerCode" label="客户编号"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerName')" prop="customerName" label="客户编号"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCode')" prop="goodsCode" label="商品编号"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('storeCode')" prop="storeCode" label="店内码"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxPrice')" prop="taxPrice" label="含税单价"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('noTaxPrice')" prop="noTaxPrice" label="未税单价"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxBoxPrice')" prop="taxBoxPrice" label="含税箱价"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('noTaxBoxPrice')" prop="noTaxBoxPrice" label="未税箱价"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('status')" prop="status" label="状态">-->
<!--          <template slot-scope="scope">-->
<!--            {{ dict.label.common_status[scope.row.status] }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-permission="['admin','basCustomerContractPrice:edit','basCustomerContractPrice:del']"-->
<!--                         label="操作" width="150px" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <udOperation-->
<!--                :data="scope.row"-->
<!--                :permission="permission"-->
<!--            />-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
import crudBasCustomerContractPrice from '@/api/erp/basCustomerContractPrice'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import {getTypeList} from "@/api/erp/basGoodsType";
import {getPriceSuitInfo} from "@/api/erp/basGoods";

import { publicListKey } from "@/utils/key";
import {getHeaderProperties} from "@/api/erp/headerProperties";
import {tablemixins} from "@/mixins/tablemixins";
import  jTableColumnConfig  from "@/components/jTableColumnConfig/jTableColumnConfig";

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '客户合同价',
  url: 'api/basCustomerContractPrice',
  sort: 'code,asc',
  crudMethod: {...crudBasCustomerContractPrice}
})
const defaultForm = {
  id: null,
  code: null,
  name: null,
  type: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  storeCode: null,
  goodsId: null,
  goodsCode: null,
  goodsName: null,
  barcode: null,
  boxBarcode: null,
  helpSign: null,
  model: null,
  goodsBrandId: null,
  goodsBrandCode: null,
  goodsBrandName: null,
  goodsTypeId: null,
  goodsTypeCode: null,
  goodsTypeName: null,
  goodsTagId: null,
  goodsTagCode: null,
  goodsTagName: null,
  taxPrice: null,
  noTaxPrice: null,
  taxBoxPrice: null,
  noTaxBoxPrice: null,
  seq: null,
  status: null,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  thirdUnitCount: null
}
export default {
  name: 'BasCustomerContractPrice',
  components: {pagination, crudOperation, rrOperation, udOperation, Treeselect,jTableColumnConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),publicListKey,tablemixins],
  dicts: ['t_bas_customer_contract_price_type', 'common_status'],
  data() {
    return {
      priceSuitList:[],
      oldGoods:{

      },
      permission: {
        add: ['admin', 'basCustomerContractPrice:add'],
        edit: ['admin', 'basCustomerContractPrice:edit'],
        del: ['admin', 'basCustomerContractPrice:del'],
        import: ['admin', 'basCustomerContractPrice:import'],
        export: ['admin', 'basCustomerContractPrice:export'],
        copy: ['admin', 'basCustomerContractPrice:copy'],
        upload: ['admin', 'basCustomerContractPrice:upload'],
        download: ['admin', 'basCustomerContractPrice:download'],
        enable: ['admin', 'basCustomerContractPrice:enable'],
        disable: ['admin', 'basCustomerContractPrice:disable'],
      },
      rules: {
        goodsId: [
          {required: true, message: '商品id不能为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '编码不能为空', trigger: 'blur'}
        ],
      },
      typeList: [],
      taxRate: 100

    }
  },
  watch: {
    // 'form.goodsId'(n,o){
    //   if (n){
    //     getPriceSuitInfo({goodsId:n,customerId:this.form.customerId}).then(res=>{
    //       this.priceSuitList = res.content
    //     })
    //   }else {
    //     this.priceSuitList = []
    //   }
    // }
  },
  created() {
    this.getTypeList()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })},
  methods: {
    changePrice(i) {
      // //当税率修改时，未税单价自动计算
      //先计算单价和总价

      const boxUnitCount = this.form.boxUnitCount

      if (i == 1) {
        //单价计算箱价
        this.form.taxBoxPrice = this.formatNum(boxUnitCount * this.form.taxPrice)
      } else {
        this.form.taxPrice = this.formatNum(this.form.taxBoxPrice / boxUnitCount)
      }

      this.form.noTaxPrice = this.formatNum(this.form.taxPrice * this.taxRate / 100)
      this.form.noTaxBoxPrice = this.formatNum(this.form.taxBoxPrice * this.taxRate / 100)
      // this.form.saleNoTaxPrice = this.formatNum( this.saleTaxPrice *  this.taxRate / 100)
      // this.form.saleNoTaxBoxPrice = this.formatNum( this.saleTaxBoxPrice *  this.taxRate / 100)

    },
    // getBrandList() {
    //   getBrandList({page: 0, size: 999}).then(res => {
    //     this.brandList = res.data.content
    //   })
    // },
    getTypeList() {
      getTypeList({page: 0, size: 999}).then(res => {
        this.typeList = res
      })
    },
    billComputedPrice(type){
      if (type === 'billTaxPrice'){
        this.form.billTaxBoxPrice = Number(this.form.billTaxPrice)*Number(this.form.boxUnitCount)
      }else {
        this.form.billTaxPrice = (Number(this.form.billTaxBoxPrice)/Number(this.form.boxUnitCount)).toFixed(2)
      }
      this.$forceUpdate()
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    //默认保留6位
    formatNum: function (num, n = 6) {
      n = n ? parseInt(n) : 0;
      if (n <= 0) {
        return Math.round(num);
      }
      num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
      num = Number(num).toFixed(n); //补足位数
      return num;
    },

    changeCustomer(data) {
      //将选择的商品部分属性传给表单，用于显示
      this.form.customerCode = data.code
      const _this = this
      if (this.form.customerId && this.form.goodsId){
        getPriceSuitInfo({goodsId:this.form.goodsId,customerId:this.form.customerId}).then(res=>{
          if (res.content.length){
            _this.form.noTaxBoxPrice = res.content[0].noTaxBoxPrice
            _this.form.noTaxPrice = res.content[0].noTaxPrice
            _this.form.taxBoxPrice =res.content[0].taxBoxPrice
            _this.form.taxPrice = res.content[0].taxPrice
            _this.form.billTaxPrice = res.content.saleTaxPrice
            _this.form.billTaxBoxPrice = res.content.saleTaxBoxPrice
          }else {
            _this.form.noTaxBoxPrice = _this.oldGoods.noTaxBoxPrice
            _this.form.noTaxPrice = _this.oldGoods.noTaxPrice
            _this.form.taxBoxPrice = _this.oldGoods.taxBoxPrice
            _this.form.taxPrice = _this.oldGoods.taxPrice
            _this.form.billTaxPrice = _this.form.taxPrice
            _this.form.billTaxBoxPrice = _this.form.taxBoxPrice
          }
          // this.priceSuitList = res.content
        })
      }
    },

    //选择商品后的操作
    changeGoods(data) {
      //将选择的商品部分属性传给表单，用于显示
      this.form.goodsCode = data.code
      this.form.goodsBrandCode = data.goodsBrandCode
      this.form.goodsBrandId = data.goodsBrandId
      this.form.goodsBrandName = data.goodsBrandName
      this.form.goodsTagCode = data.goodsTagCode
      this.form.goodsTagId = data.goodsTagId
      this.form.goodsTagName = data.goodsTagName
      this.form.goodsTypeCode = data.goodsTypeCode
      this.form.goodsTypeId = data.goodsTypeId
      this.form.goodsTypeName = data.goodsTypeName
      this.form.thirdUnitCount = data.thirdUnitCount
      this.form.noTaxBoxPrice = data.saleNoTaxBoxPrice
      this.form.noTaxPrice = data.saleNoTaxPrice
      this.form.taxBoxPrice = data.saleTaxBoxPrice
      this.form.taxPrice = data.saleTaxPrice
      this.form.billTaxPrice = this.form.taxPrice
      this.form.billTaxBoxPrice = this.form.taxBoxPrice
      this.form.fourthUnitCount = data.fourthUnitCount
      this.form.boxUnitCount = data.boxUnitCount
      this.oldGoods = {
        noTaxBoxPrice: data.saleNoTaxBoxPrice,
        noTaxPrice: data.saleNoTaxPrice,
        taxBoxPrice: data.saleTaxBoxPrice,
        taxPrice: data.saleTaxPrice
      }
      this.taxRate = data.taxRate
      const _this = this
      if (this.form.customerId && this.form.goodsId){
        getPriceSuitInfo({goodsId:this.form.goodsId,customerId:this.form.customerId}).then(res=>{
          if (res.content.length){
            _this.form.noTaxBoxPrice = res.content[0].noTaxBoxPrice
            _this.form.noTaxPrice = res.content[0].noTaxPrice
            _this.form.taxBoxPrice = res.content[0].taxBoxPrice
            _this.form.taxPrice = res.content[0].taxPrice
            _this.form.billTaxPrice = res.content.saleTaxPrice
            _this.form.billTaxBoxPrice = res.content.saleTaxBoxPrice
          }else {
            _this.form.noTaxBoxPrice = _this.oldGoods.noTaxBoxPrice
            _this.form.noTaxPrice = _this.oldGoods.noTaxPrice
            _this.form.taxBoxPrice = _this.oldGoods.taxBoxPrice
            _this.form.taxPrice = _this.oldGoods.taxPrice
            _this.form.billTaxPrice = _this.form.taxBoxPrice
            _this.form.billTaxBoxPrice = _this.form.taxPrice
          }
          // this.priceSuitList = res.content
        })
      }
    },
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
